package com.codeest.geeknews.util.notify;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.codeest.geeknews.R;
import com.codeest.geeknews.model.bean.MusicInfo;
import com.codeest.geeknews.ui.main.activity.MusicActivity;

import java.util.HashMap;
import java.util.Map;


public class MusicNotifyManager {
    public static final String ACTION_PAUSE_NOTICE = "cn.aman.reader.action.pause";
    private static final int PROGRESS_MAX = 1000;

    private AbstractFactory notifyFactory;
    // MusicNotifyManager ： 是状态栏通知的管理类，负责发通知、清楚通知等。
    private NotificationManager manager;
    // 定义Map来保存Notification对象
    private Map<Integer, NotificationCompat.Builder> builderMap = null;
    private Map<Integer, Notification> notificationMap = null;

    private Context context;
    private MusicInfo musicInfo;

    public MusicNotifyManager(Context context) {
        this.context = context;
        notifyFactory = new NotifyFactory();
        manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        builderMap = new HashMap<>();
        notificationMap = new HashMap<>();
    }

    /**
     * @param notificationId-
     * @param musicInfo-
     */
    public void showNotification(final int notificationId, MusicInfo musicInfo) {
        // 判断对应id的Notification是否已经显示， 以免同一个Notification出现多次
        if (!notificationMap.containsKey(notificationId)) {
            final RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.notification_music);
            String titleAndArtist = musicInfo.getTitle() + "-" + musicInfo.getArtist();
            remoteViews.setTextViewText(R.id.tv_title, titleAndArtist);
            remoteViews.setProgressBar(R.id.pBar, PROGRESS_MAX, 0, true);
            remoteViews.setInt(R.id.btn_pause, "setColorFilter", Color.parseColor("#122B3B"));//改变按钮的图像颜色：
            //跳转到MusicActivity
            int requestCode = (int) SystemClock.uptimeMillis();
            Intent intentActivity = new Intent(context, MusicActivity.class);
            PendingIntent piActivity = PendingIntent.getActivity(context, requestCode, intentActivity, PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.notice_view, piActivity);
            //暂停通知
            int requestCode1 = (int) SystemClock.uptimeMillis();
            Intent intent1 = new Intent(ACTION_PAUSE_NOTICE);
            PendingIntent piPause = PendingIntent.getBroadcast(context, requestCode1, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.btn_pause, piPause);
            //
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
            builder.setContentTitle("Notification");
            builder.setContentText("自定义通知栏示例");
            builder.setSmallIcon(R.mipmap.ic_launcher);
            //builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.push));
            builder.setAutoCancel(false);
            builder.setOngoing(true);
            builder.setShowWhen(false);
            builder.setContent(remoteViews);
            builder.setCustomBigContentView(remoteViews);
            final Notification notification = builder.build();
            //
            manager.notify(notificationId, notification);
            Glide.with(context.getApplicationContext())//这里不要用Activity,因为activity转到后台后Glide会暂停下载图片导致图片空白
                    .load(musicInfo.getPicture())
                    .asBitmap()
                    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                    .into(new SimpleTarget<Bitmap>(100, 100) {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                            remoteViews.setImageViewBitmap(R.id.icon, resource);
                            manager.notify(notificationId, notification);
                        }

                        @Override
                        public void onLoadFailed(Exception e, Drawable errorDrawable) {
                            super.onLoadFailed(e, errorDrawable);
                        }
                    });
            //
            builderMap.put(notificationId, builder);// 存入Map中
            notificationMap.put(notificationId, notification);// 存入Map中
        }
    }

    /**
     * 更新进度条
     *
     * @param notificationId-
     * @param downloadInfo-
     */
    public void updateProgress(int notificationId, MusicInfo downloadInfo) {
        if (downloadInfo.getDuration() == 0) {
            return;
        }
        int progress = (int) (PROGRESS_MAX * downloadInfo.getProgress() / downloadInfo.getDuration());
        NotificationCompat.Builder notifyBuilder = builderMap.get(notificationId);
        Notification notify = notificationMap.get(notificationId);
        if (null != notify) {
            // 修改进度条
            notifyBuilder.getBigContentView().setProgressBar(R.id.pBar, PROGRESS_MAX, progress, false);
            manager.notify(notificationId, notify);
        }
    }

    /**
     * 更新播放按钮状态
     *
     * @param notificationId-
     * @param play-
     */
    public void updatePlayButton(int notificationId, boolean play) {
        NotificationCompat.Builder notifyBuilder = builderMap.get(notificationId);
        Notification notify = notificationMap.get(notificationId);
        if (null != notify) {
            int backresid = play ? R.drawable.selector_player_btn_play : R.drawable.selector_player_btn_pause;
            notifyBuilder.getBigContentView().setInt(R.id.btn_pause, "setImageResource", backresid);//重新设置按钮状态
            manager.notify(notificationId, notify);
        }
    }


    public void remove(int notificationId) {
        manager.cancel(notificationId);
        builderMap.remove(notificationId);
        notificationMap.remove(notificationId);
    }
}
